import { reactive, computed, watch, onBeforeUnmount } from 'vue';
import { keyboardList } from '@/common/js/keyboard.js';
import { chinesePunctuationToEnglish } from '@/common/utils/index.js';
import useTyping from './useTyping.js';
export default function(getContent) {
	const {
		typing,
		setTyping,
		recordSpeed,
		itemClassName,
		showErrorClass,
		progress,
		accuracyKey,
		accuracyWord,
		courseComplete,
		next,
		queryRect,
		typingSound,
		gameSound
	} = useTyping(getContent, keydownFun);
	typing.type = 'BASE';
	typing.content = getContent().courseText[0].split('');
	typing.courseContentStr = getContent().courseText[0];
	typing.allow_mistakes = !(['LEARN', 'REVIEW'].indexOf(getContent().courseType) > -1);
	// 监听并设置滚动条位置
	watch(() => typing.current, async (newVal) => {
		const element = document.getElementById('bd_view');
		const { top: bdTop } = await queryRect('bd');
		const { top: itemTop } = await queryRect('item-' + newVal);
		const diff = itemTop - bdTop + element.scrollTop;
		element.scrollTop = diff;
	})
	// 描述相关
	const desc = computed((v) => {
		return v => {
			const find = keyboardList.find(item => item.key == v);
			return find.desc;
		}
	})
	// 键盘事件处理
	function keydownFun(e) {
		const find = keyboardList.find(item => item.keyCode == e.keyCode);
		if (find) {
			if (progress.value >= 100) {
				return next(find);
			}
			switch (find.key) {
				case 'Backspace':
					if (typing.current > 0) {
						typing.current--;
						setTyping('back', '');
					}
					typingSound('backspace');
					break;
				default:
					const text = find.key.toLowerCase();
					if (chinesePunctuationToEnglish(typing.content[typing.current]) == text) {
						setTyping('success', text);
						typing.current++;
						typingSound('success');
					} else {
						typing.showError = true;
						setTimeout(() => {
							typing.showError = false;
						}, 60)
						setTyping('error', text);
						if (typing.allow_mistakes) typing.current++;
						typingSound('error');
					}
					break;
			}
			if (!typing.startTime) {
				typing.timer = setInterval(() => {
					typing.time++;
					recordSpeed();
				}, 1000)
				typing.startTime = Date.now();
			}
		}
	}
	return {
		typing,
		successRate: accuracyKey,
		desc,
		progress,
		showErrorClass,
		itemClassName,
		courseComplete
	}
}